#include <stdio.h>  
#include <unistd.h>  
#include <sys/time.h>  
#include <string.h>  
#include <stdlib.h>
#include <time.h>
#include <lua.h>  
#include <lauxlib.h>


#define _LINE_LENGTH 300 
 
static int GetCpuMem(lua_State *L) 
{ 
    float cpu=0; 
    size_t mem=0; 
    int pid=getpid(); 
    int tid=-1; 

    char cmdline[100]; 
    sprintf(cmdline, "ps -o %%cpu,rss,%%mem,pid,tid -mp %d", pid); 
    FILE *file; 
    file = popen(cmdline, "r"); 
    if (file == NULL)  
    { 
        return 0; 
    } 
    char line[_LINE_LENGTH]; 
    float l_cpuPrec=0; 
    int l_mem=0; 
    float l_memPrec=0; 
    int l_pid=0; 
    int l_tid=0; 
    if (fgets(line, _LINE_LENGTH, file) != NULL)  
    { 
        if (fgets(line, _LINE_LENGTH, file) != NULL)  
        { 
            sscanf( line, "%f %d %f %d -", &l_cpuPrec, &l_mem, &l_memPrec, &l_pid ); 
            cpu = l_cpuPrec; 
            mem = l_mem/1024; 
            if( tid == -1 ) 
                ;
            else 
            { 
                while( fgets(line, _LINE_LENGTH, file) != NULL ) 
                { 
                    sscanf( line, "%f - - - %d", &l_cpuPrec, &l_tid ); 
                    if( l_tid == tid ) 
                    { 
                        printf("cpuVal is tid:%d\n",tid); 
                        cpu = l_cpuPrec; 
                        break; 
                    } 
                } 
                if( l_tid != tid ) 
                    printf("TID not exist\n"); 
            } 
        } 
        else 
            printf("PID not exist\n"); 
    } 
    else 
        printf("Command or Parameter wrong\n"); 
    pclose(file); 
    lua_pushnumber(L,cpu);
    lua_pushnumber(L,mem);
    return 2; 
}

static int GetTime(lua_State *L) 
{
    struct timeval tv;
    gettimeofday(&tv,NULL);
    unsigned long long us = (tv.tv_sec*1000000+tv.tv_usec);
    lua_pushnumber(L, us);
    return 1;
}

LUAMOD_API int luaopen_sysinfo(lua_State *L) 
{  
    luaL_Reg l[] = {  
        { "getinfo",GetCpuMem}, 
        { "gettime",GetTime},
        { NULL, NULL },  
    };
    luaL_newlib(L,l);
    return 1;  
}   
